<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖</title>
</head>

<body>

    <input id="input1" placeholder="防抖" type="text">
    <input id="input2" placeholder="节流" type="text">

    <script>
        function submit() {
            console.log(arguments[0]);
            console.log('提交数据', arguments[0].data);
        }

        // 防抖
        function debounce(fn, delay = 500) {
            let timer = null
            return function () {
                let arg = arguments
                let context = this
                if (timer !== null) clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(context, arg)
                }, delay)
            }
        }

        let inp = document.querySelector('#input1')
        inp.oninput = debounce(submit)

        // 节流 时间戳版：

        function throttleD(fn, wait = 500) {


            let startTimer = 0
            return function () {
                let context = this
                let arg = arguments
                let now = Date.now()
                if (now - startTimer > wait) {
                    fn.apply(context, arg)
                    startTimer = now
                }
            }
        }
        // 节流 定时器版：
        function throttleT(fn, wait = 500) {
            let timeout;
            return function () {
                let context = this
                let arg = arguments
                if (!timeout) {
                    timeout = setTimeout(() => {
                        timeout = null
                        fn.apply(context, arg)
                    }, wait)
                }
            }
        }

        let inp2 = document.querySelector('#input2')
        inp2.oninput = throttleD(submit)
        // inp2.oninput =  throttleT(submit)

    </script>
</body>

</html>